﻿
using System;
using System.Collections.Generic;
using System.Text;
using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Marketing.OpenLife.Models;
using Alipay.EasySDK.Payment.FaceToFace.Models;


namespace WebApi.Controllers
{
    /// <summary>
    /// 支付宝帮助类
    /// </summary>
    public class AlipayHelper
    {
        #region 支付宝配置信息 

        /// <summary>
        /// 支付宝配置信息
        /// </summary>
        public static Config config = new Config()
        {
            Protocol = "https",
            GatewayHost = "openapi.alipay.com",
            SignType = "RSA2",
            AppId = "2021004138668182",
            //应用私钥(支付宝公钥生成的RSA2私钥要转换下,不然异常,装换流程: 支付宝工具--左侧导航--第3项(格式转换)--私有放里面--点击转换),这里使用转换后的私钥
            MerchantPrivateKey = "1346",
            //支付宝公钥
            AlipayPublicKey = "1346",

            //可设置异步通知接收服务地址（可选）
            NotifyUrl = $"https://liepin-dcddutelng.cn-hangzhou.fcapp.run/ChongZhi/AlipayCallBack",

            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            EncryptKey = "sdfds=="
        };
        #endregion

        #region 支付宝预支付

        /// <summary>
        /// 支付宝预支付
        /// </summary>
        /// <param name="subject">商品名称</param>
        /// <param name="outTradeNo">订单号</param>
        /// <param name="price">金额</param>
        /// <returns></returns>
        public static string GetAlipayCode(string subject, string outTradeNo, decimal price)
        {
            Factory.SetOptions(config);//1. 设置参数（全局只需设置一次）
            try
            {
                //price = Math.Ceiling(price);

                AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().PreCreate(subject, outTradeNo, price.ToString());// 2. 发起API调用（以创建当面付收款二维码）
                if (ResponseChecker.Success(response))// 3. 处理响应或异常
                {
                    return response.QrCode;
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Msg + "，" + response.SubMsg);
                }
            }
            catch
            {
            }
            return "";
        }
        #endregion 
    }
}
